const app = getApp();

import regeneratorRuntime from '../../utils/runtime';

Page({
  data: {
    searching: false,
    searchText: "",
    searchResults: [],
    submitKeywordStatus: "",
    showingDetail: false,
    showQr: false,
    writePhotosAlbumStatus: 0,
    searchType: 'name'
  },

  onLoad() {
    this.getSetting();
  },

  showDetail(t) {
    this.setData({
      showingDetail: true,
      detailItemName: t.currentTarget.dataset.itemName,
      detailCatIndex: t.currentTarget.dataset.catIndex
    });
  },

  hideDetail(t) {
    this.setData({
      showingDetail: false
    });
  },

  onTextSearch(e) {
    const searchText = e.detail.value.trim();

    this.setData({
      searchResults: [],
      submittedKeyword: false,
      searchType: 'name',
      searchText
    });

    if (!searchText) {
      return;
    }

    app.util.request({
      module: 'cm_garbage_query',
      url: 'entry/wxapp/index',
      data: {
        op: 'search',
        keyword: searchText
      },
      showLoading: true,
      success: res => {
        const searchResults = res.data.data || '';

        searchResults && this.setData({
          searchResults
        })

        console.log('========searchResults', searchResults);


        if (!searchResults || searchResults.length <= 0) {
          wx.showModal({
            title: '系统提示',
            content: '没有找到您要的结果',
            showCancel: false
          });
        }
      },
    });
  },

  clearSearchText() {
    this.setData({
      searchText: "",
      searchResults: [],
    });
  },

  authorizeWritePhotosAlbum(t) {
    var e = this;
    wx.authorize({
      scope: "scope.writePhotosAlbum",
      success: function () {
        e.saveQrToAlbum();
      },
      fail: function () {
        e.setData({
          writePhotosAlbumStatus: 2
        });
      }
    });
  },

  setKeyword(e) {
    this.setData({
      searchText: e.detail.value
    })
  },

  async onImgSearch() {
    try {
      this.setData({
        searchType: 'file',
        searchResults: []
      })

      const filePath = await this.chooseImage();
      const result = await this.uploadImage(filePath);
      const filepath = result.filename;

      app.util.request({
        module: 'cm_garbage_query',
        url: 'entry/wxapp/index',
        data: {
          op: 'picSearch',
          type: 'file',
          filepath
        },
        showLoading: true,
        success: res => {
          console.log('======res', res);
          if(!res.data.data){
            wx.showModal({
              title: '系统提示',
              content: '暂无搜索结果，请尝试重拍',
              showCancel: false,
            })
          }
          const searchResults = res.data.data && res.data.data.data || "";
          searchResults && this.setData({
            searchResults
          })
        },
      });
    } catch (error) {
      console.log('=======onImgSearch error', error);
    }
  },

  chooseImage() {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
          const tempFilePaths = res.tempFilePaths && res.tempFilePaths[0] || '';
          resolve(tempFilePaths);
        },
        fail: res => {
          reject(res);
        }
      })
    });
  },

  uploadImage(filePath) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '图片上传中',
        icon: 'loading',
        mask: true,
      });

      const url = app.util.url('utility/file/upload', {
        type: 'image',
        thumb: '0',
      });

      wx.uploadFile({
        url,
        filePath,
        name: 'file',
        success: res => {
          const result = JSON.parse(res.data);

          this.setData({
            searchPhoto: result.url,
          })

          resolve(result);
        },
        fail: res => {
          wx.showModal({
            title: '系统提示',
            content: '上传失败',
          });
          reject(res);
        },
        complete: res => {
          wx.hideLoading();
        }
      });
    });
  },

  getSetting() {
    app.util.request({
      module: 'cm_garbage_query',
      url: 'entry/wxapp/index',
      data: {
        op: 'getSetting'
      },
      showLoading: true,
      success: res => {
        const { share_cover: shareCover = '', share_title: shareTitle ='' } =  res.data.data;
       this.setData({
          shareCover,
          shareTitle
        })
      },
    });
  },

  goHome() {
    const isCompanyCloudTemplate = Number(app.siteInfo.isCloudTemplate) === 1;
    if (isCompanyCloudTemplate) {  // 企业云端发布
      app.util.navigateTo('ws_micro_company_collection/pages/index/index', '', true);
      return;
    }
    let appJson = app.siteInfo.appJson[app.tabbarindex || 0];
    const url = appJson.homePage || (appJson.tabBar && appJson.tabBar.list && appJson.tabBar.list[0].pagePath);
    app.util.navigateTo(url, {}, 'all');
  },

  onShareAppMessage() {
    const { shareCover: imageUrl = '', shareTitle: title = '' } = this.data;
    return {
      title,
      path:'/cm_garbage_query/pages/search/search',
      imageUrl
    };
  },
});